// (C) Copyright 2009, 2010 Communications Programming, Inc.
/***************************************************************************************************************
*  Name: readVexUltraSonic3
*
*  Description: Function to read the VexUltraSonic unit
*
*  Timer T2 is used delayT2_us() and delayT2_ms()
*
*  This routine uses pins RD2 and RD3:
*
*  RD2 connects to the yellow signal pin marked Input on the Vex US device.
*  RD3 connects to the orange signal pin marked Input on the Vex US device.
*
*  +5 is connected to the red pin of both input and output cables.
*  GND is connected to the black pin of both input and output cables.
*
*  Calling Parameters:
*  
*  int readVexUltraSonic3();
*
*  Returns:    The distance in units of approx 1/4 inch to object
*
*  Revision History:
*  Date    Who  Comments
*  ------  ---  -----------------------------------------------------------------------------------------
*  100425  RLP   Created.
*
***************************************************************************************************************/

#include "userLib.h"

// init routine called during initialization to set pin direction

void readVexUltraSonic3_init(void)
{
	TRISDbits.TRISD2 = 0;	// specify RD2 as output 
	TRISDbits.TRISD3 = 1;	// specify RD3 as input 
}

int readVexUltraSonic3()
{
   int            cntr = 0;
   unsigned char  pinVal;

   // generate a short pulse to initiate the ping
   
   LATDbits.LATD2 = 1;
   delayT2_ms(13);      // guarantee min reset time between US pings
   LATDbits.LATD2 = 0;
   
   // wait for US output signal pin goes high (ping initiated)
   
   pinVal = PORTDbits.RD3;
   while( pinVal == 0 )
      pinVal = PORTDbits.RD3;

   // start cntr, 1/4 inch per loop
   
   while( pinVal == 1 )
   {
      delayT2_us(90);
      ++cntr;
      pinVal = PORTDbits.RD3;
   }
   
   // output pin dropped (ping return detected)

   return(cntr);
}
